#!/bin/bash

# 健康检查脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
BACKEND_URL="http://localhost:7001"
FRONTEND_URL="http://localhost:8080"
CONTAINER_NAME="git-env-dev"

echo -e "${BLUE}执行健康检查...${NC}"

# 检查容器是否运行
echo -e "${BLUE}检查容器状态...${NC}"
if docker ps --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
    echo -e "${GREEN}✓ 容器 ${CONTAINER_NAME} 正在运行${NC}"
else
    echo -e "${RED}✗ 容器 ${CONTAINER_NAME} 未运行${NC}"
    exit 1
fi

# 检查PostgreSQL
echo -e "${BLUE}检查PostgreSQL...${NC}"
if docker exec "${CONTAINER_NAME}" pg_isready -h localhost -p 5432 -U postgres &>/dev/null; then
    echo -e "${GREEN}✓ PostgreSQL 运行正常${NC}"
else
    echo -e "${RED}✗ PostgreSQL 连接失败${NC}"
fi

# 检查Redis
echo -e "${BLUE}检查Redis...${NC}"
if docker exec "${CONTAINER_NAME}" redis-cli -h localhost -p 6379 ping | grep -q "PONG"; then
    echo -e "${GREEN}✓ Redis 运行正常${NC}"
else
    echo -e "${RED}✗ Redis 连接失败${NC}"
fi

# 检查FastAPI后端
echo -e "${BLUE}检查FastAPI后端...${NC}"
if curl -s -f "${BACKEND_URL}/health" &>/dev/null || curl -s -f "${BACKEND_URL}/docs" &>/dev/null; then
    echo -e "${GREEN}✓ FastAPI 后端运行正常${NC}"
else
    echo -e "${YELLOW}⚠ FastAPI 后端可能还在启动中${NC}"
fi

# 检查Vue.js前端
echo -e "${BLUE}检查Vue.js前端...${NC}"
if curl -s -f "${FRONTEND_URL}" &>/dev/null; then
    echo -e "${GREEN}✓ Vue.js 前端运行正常${NC}"
else
    echo -e "${YELLOW}⚠ Vue.js 前端可能还在启动中${NC}"
fi

# 检查Celery Worker
echo -e "${BLUE}检查Celery Worker...${NC}"
if docker exec "${CONTAINER_NAME}" pgrep -f "celery.*worker" &>/dev/null; then
    echo -e "${GREEN}✓ Celery Worker 运行正常${NC}"
else
    echo -e "${RED}✗ Celery Worker 未运行${NC}"
fi

# 检查Celery Beat
echo -e "${BLUE}检查Celery Beat...${NC}"
if docker exec "${CONTAINER_NAME}" pgrep -f "celery.*beat" &>/dev/null; then
    echo -e "${GREEN}✓ Celery Beat 运行正常${NC}"
else
    echo -e "${RED}✗ Celery Beat 未运行${NC}"
fi

# 检查端口占用
echo -e "${BLUE}检查端口占用...${NC}"
for port in 7001 8080; do
    if netstat -ln | grep ":${port} " &>/dev/null; then
        echo -e "${GREEN}✓ 端口 ${port} 正在被监听${NC}"
    else
        echo -e "${YELLOW}⚠ 端口 ${port} 未被监听${NC}"
    fi
done

# 检查日志文件
echo -e "${BLUE}检查日志文件...${NC}"
for log_file in "logs/app/fastapi.log" "logs/app/vuejs.log" "logs/celery/celery-worker.log"; do
    if [ -f "$log_file" ]; then
        echo -e "${GREEN}✓ 日志文件 ${log_file} 存在${NC}"
    else
        echo -e "${YELLOW}⚠ 日志文件 ${log_file} 不存在${NC}"
    fi
done

# 显示容器资源使用情况
echo -e "${BLUE}容器资源使用情况:${NC}"
docker stats "${CONTAINER_NAME}" --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}"

echo -e "${GREEN}健康检查完成!${NC}"